// 创建群组、获取群组列表 
import { Request, Response, NextFunction } from 'express';
import { CreateGroupDTO, GroupMembersDTO } from '../dto/group.dto';
import * as groupService from '../services/group.service';
import { formatDate } from '../utils/format';

const groupToClient = (g: any) => ({
  id: g.id.toString(),
  name: g.name,
  avatar: g.avatar,
  owner_id: g.owner_id.toString(),
  created_at: formatDate(g.created_at),
  updated_at: formatDate(g.updated_at)
});

export const createGroup = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const input = CreateGroupDTO.parse(req.body);
    const uid = Number((req as any).user.id);
    const group = await groupService.createGroup(uid, input);
    res.safeJson(groupToClient(group), '群组创建成功');
  } catch (err) {
    next(err);
  }
};

export const listGroups = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const uid = Number((req as any).user.id);
    const groups = await groupService.getUserGroups(uid);
    res.safeJson(groups, '获取成功');
  } catch (err) {
    next(err);
  }
};

export const getGroupMembers = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const groupId = Number(req.params.id);
    const members = await groupService.getGroupMembers(groupId);
    res.safeJson(members, '获取成员成功');
  } catch (err) {
    next(err);
  }
};

export const inviteToGroup = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const groupId = Number(req.params.id);
   const { user_ids } = GroupMembersDTO.parse(req.body);
    const inviterId = Number((req as any).user.id);
    await groupService.inviteToGroup(groupId, inviterId, user_ids);
    res.safeJson(null, '邀请成功');
  } catch (err) {
    next(err);
  }
};

export const leaveGroup = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const groupId = Number(req.params.id);
    const currentUserId = Number((req as any).user.id);
    const userIds: number[] = req.body?.user_ids || [currentUserId];

    await groupService.leaveGroup(groupId, userIds, currentUserId);
    res.safeJson(null, '退出成功');
  } catch (err) {
    next(err);
  }
};


export const deleteGroup = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const groupId = Number(req.params.id);
    const userId = Number((req as any).user.id);
    await groupService.deleteGroup(groupId, userId);
    res.safeJson(null, '群组已解散');
  } catch (err) {
    next(err);
  }
};
